﻿using Newtonsoft.Json;
using StackExchange.Redis;
using System;

namespace Business
{
    /// <summary>
    /// redis 帮助类
    /// </summary>
    public class RedisHelper 
    {
        private ConnectionMultiplexer redis { get; set; } 
        private IDatabase db { get; set; }
        public RedisHelper(string connection)
        {
            redis = ConnectionMultiplexer.Connect(connection);
            db = redis.GetDatabase();
        }
        // public static string connectionString { get { return AppConfigurtaionServices.Configuration["Appsettings:RedisConnection"]; } }
        // 调用实例
        //RedisHelper redisHelper = new RedisHelper("127.0.0.1:6379,abortConnect = false,password=123123");
        //string value = "abcdefg";
        //bool r1 = redisHelper.SetValue("mykey", value);

        /// <summary>
        /// 增加/修改
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool SetValue(string key, string value)
        {
            return db.StringSet(key, value);
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetValue(string key)
        {
            return db.StringGet(key);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool DeleteKey(string key)
        {
            return db.KeyDelete(key);
        }

        /// <summary>
        /// 保存实体并设置过期时间
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">键值</param>
        /// <param name="t">实体</param>
        /// <param name="time">过期时间</param>
        /// <returns></returns>
        public bool SetEntity<T>(string key, T t, TimeSpan time)
        {
            if (string.IsNullOrEmpty(key)) throw new ArgumentException(string.Format("key实例名称为空"));
            var value = JsonConvert.SerializeObject(t);
            return db.StringSet(key, value, time);
        }

        /// <summary>
        /// 根据Key获取值
        /// </summary>
        /// <typeparam name="T">实体</typeparam>
        /// <param name="key">键值</param>
        /// <returns></returns>
        public T GetEntity<T>(string key) where T : class
        {
            var strValue = db.StringGet(key);
            return string.IsNullOrEmpty(strValue) ? null : JsonConvert.DeserializeObject<T>(strValue);
        }
    }
}
